﻿using EasyNetQ;
using EasyNetQ.Topology;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public void ReceiveQueue<T>(string queue, Action<T> process) where T : class
        {
            try
            {
                var _connectionConfigName = "rabbitmq-default";
                var _connectionString = ConfigurationManager.AppSettings[_connectionConfigName] ?? "";
                var bus = RabbitHutch.CreateBus(_connectionString);
                bus.Receive(queue, process);
                richTextBox1.AppendText(process.ToString());
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText(ex.Message);
                //logger.ErrorFormat(StringUtils.FormatException(ex));
            }

        }
        private void button1_Click(object sender, EventArgs e)
        {
            var _connectionConfigName = "rabbitmq-default";
            var _connectionString = ConfigurationManager.AppSettings[_connectionConfigName] ?? "";
            var bus = RabbitHutch.CreateBus(_connectionString);
            var adbus = bus.Advanced;
            var exchange = adbus.ExchangeDeclare("fanoutec", EasyNetQ.Topology.ExchangeType.Fanout);
            var queue = CreateQueue(adbus, "fanouteckequeue");
            adbus.Bind(exchange, queue, "fanouteckey");
            adbus.Consume(queue, (body, properties, info) => Task.Factory.StartNew(() =>
            {
                try
                {
                    this.Invoke(new Action(() =>



                    {



                        richTextBox1.AppendText(Encoding.UTF8.GetString(body));



                    }));


                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);

                }


            }));

            //FanoutConsume<Ec>((t) => richTextBox1.AppendText(JsonConvert.SerializeObject(t)), "fanoutec", "fanouteckequeue", "fanouteckey");

        }

        private void Rabbitmqoperate_OnMqMessageReceived_ECStates(Ec obj)
        {
            richTextBox1.AppendText(obj.ToString());
        }

        private static IQueue CreateQueue(IAdvancedBus adbus, string queueName)
    {
        if (adbus == null) return null;
        if (string.IsNullOrEmpty(queueName)) return adbus.QueueDeclare();
        return adbus.QueueDeclare(queueName);
    }
    public static void FanoutConsume<T>(Action<T> handler, string exChangeName, string queueName, string routingKey) where T : class
    {

    }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
